﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SmallERP.MODEL;
using SmallERP.DAL;
using SmallERP.Bll.Com;
using SmallERP.MODEL.FoundationModel;
using SmallERP.MODEL.MakeBigPic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Runtime.InteropServices;
using SmallERP.COM;

namespace SmallERP.HostBll.MakeBigPic
{
    /// <summary>
    /// 关于大板的各种处理类
    /// </summary>
    public class BoardBLL
    {
        public string addr { get; set; }
        public int port { get; set; }
        private string _dogCode;

        /// <summary>
        /// 移动文件，文件夹
        /// </summary>
        /// <param name="src"></param>
        /// <param name="dst"></param>
        /// <param name="flag">1如果文件存在，则替换；2如移动到不同的卷，则复制文件并删除原来的文件；3移动操作在系统重启后才真正执行</param>
        /// <returns></returns>
        [DllImport("kernel32", EntryPoint = "MoveFileEx", CharSet = CharSet.Unicode)]
        public static extern bool MoveFileEx(string src, string dst, long flag);
        private string GetDogCode()
        {
            if (string.IsNullOrEmpty(_dogCode))
            {
                _dogCode = UnityMethod.GetDogCode(addr, port);
            }

            return _dogCode;
        }
        
        /// <summary>
        /// 更新大板
        /// </summary>
        /// <param name="upBoard"></param>
        public static void UpdateBoard(int boardId, int boardStatus, string remark)
        {
            //using (smallerpDataContext db = new smallerpDataContext())
            //{
            //    Board curB = db.Board.FirstOrDefault(b => b.BoardId == boardId);
            //    if (curB != null)
            //    {
            //        curB.LastPrintTime = UnityMethod.GetSystemTime();
            //        curB.Status = boardStatus;
            //        curB.Remark = remark;
            //    }
            //    db.SaveChanges();
            //}

            string UpdateBoard = "update board set LastPrintTime='" + DateTime.Now + "',Status=" + boardStatus + ",Remark='" + remark + "' where boardid=" + boardId;
            int a = SmallERP.DAL.AccessHelper.ExecuteNonQuery(UpdateBoard);

        }
        /// <summary>
        /// 更新大板
        /// </summary>
        /// <param name="upBoard"></param>
        public static int UpdateBoard2(int boardId, int boardStatus, string remark)
        {
            //using (smallerpDataContext db = new smallerpDataContext())
            //{
            //    Board curB = db.Board.FirstOrDefault(b => b.BoardId == boardId);
            //    if (curB != null)
            //    {
            //        curB.LastPrintTime = UnityMethod.GetSystemTime();
            //        curB.Status = boardStatus;
            //        curB.Remark = remark;
            //    }
            //    db.SaveChanges();
            //}

            string UpdateBoard = "update board set LastPrintTime='" + DateTime.Now + "',Status=" + boardStatus + ",Remark='" + remark + "' where boardid=" + boardId;
            return  SmallERP.DAL.AccessHelper.ExecuteNonQuery(UpdateBoard);

        }
        /// <summary>
        /// 从数据库中得到一个可用来生成大图的板
        /// </summary>
        /// <returns></returns>
        public BoardInfo_MakeBigPic GetOneBoardToProduct()
        {
            BoardInfo_MakeBigPic resultBoard = new BoardInfo_MakeBigPic();
            int waitProductStatus = (int)SmallERP.COM.Status.EnumBoardStatus.waitProduct;
            
            int errorProductStatus = (int)SmallERP.COM.Status.EnumBoardStatus.Error;
            OleDbConnection oleconn = AccessHelper.OpenMyConnection();
            using (var tran = oleconn.BeginTransaction())
            {
                string getBoardSql = "select  * from board where status=" + waitProductStatus + " order by PrintPriority desc,CreateTime";
                DataTable tableBoard = AccessHelper.dataTable(getBoardSql, oleconn, tran);
                int waitBoardCount = tableBoard.Rows.Count;
                if (waitBoardCount <= 0)
                {
                    return null;
                }
               
                resultBoard.AllCount = waitBoardCount.ToString();


                string getErrorBoardSql = "select  * from board where status=" + errorProductStatus + " order by PrintPriority desc,CreateTime";
                DataTable tableErrorBoard = AccessHelper.dataTable(getErrorBoardSql, oleconn, tran);
                int errorBoardCount = tableBoard.Rows.Count;
                resultBoard.ErrorBoardNum = errorBoardCount;

                int DPI = Convert.ToInt32(tableBoard.Rows[0]["DPI"]);
                int boardTempleteID = Convert.ToInt32(tableBoard.Rows[0]["TemplateID"]);
                resultBoard.BoardBaseInfo = new Board_Info()
                {
                    AutoPoint = Convert.ToString(tableBoard.Rows[0]["AutoPoint"]),
                    BoardId = Convert.ToInt32(tableBoard.Rows[0]["BoardId"]),
                    CreateTime = Convert.ToDateTime(tableBoard.Rows[0]["CreateTime"]),
                    DPI = Convert.ToInt32(tableBoard.Rows[0]["DPI"]),
                    Height = Convert.ToInt32(tableBoard.Rows[0]["Height"]),
                    LastPrintTime = Convert.ToDateTime(tableBoard.Rows[0]["LastPrintTime"]),
                    Length = Convert.ToInt32(tableBoard.Rows[0]["Length"]),
                    PaperFaceId = Convert.ToInt32(tableBoard.Rows[0]["PaperFaceId"]),
                    PaperTypeId = Convert.ToInt32(tableBoard.Rows[0]["PaperTypeId"]),
                    PicPath = Convert.ToString(tableBoard.Rows[0]["PicPath"]),
                    PrinterId = Convert.ToInt32(tableBoard.Rows[0]["PrinterId"]),
                    PrintNum = Convert.ToInt32(tableBoard.Rows[0]["PrintNum"]),
                    PrintPaperId = Convert.ToInt32(tableBoard.Rows[0]["PrintPaperId"]),
                    PrintPriority = Convert.ToInt32(tableBoard.Rows[0]["PrintPriority"]),
                    Remark = Convert.ToString(tableBoard.Rows[0]["Remark"]),
                    Status = Convert.ToInt32(tableBoard.Rows[0]["status"]),
                    WasteRate = Convert.ToInt32(tableBoard.Rows[0]["WasteRate"]) ,
                    BoardProcudtType = Convert.ToInt32(tableBoard.Rows[0]["BoardProcudtType"])
                };
                
                string QueryPrinterSetting = "select * from PrinterSeting where printerid=" + resultBoard.BoardBaseInfo.PrinterId + " and papertypeid=" + resultBoard.BoardBaseInfo.PaperTypeId;
                DataTable tablePS = AccessHelper.dataTable(QueryPrinterSetting, oleconn, tran);
                if (tablePS.Rows.Count > 0)
                {
                    resultBoard.AddSharpen = Convert.ToInt32(tablePS.Rows[0]["Sharpening"]);
                    resultBoard.IccPath = Convert.ToString(tablePS.Rows[0]["IccPath"]);
                }
                else
                {
                    resultBoard.AddSharpen = 0;
                    resultBoard.IccPath = @"\\";
                }
                string QueryPrinter = "select IsTransverse,IsMiddle,PName,PrinterType,IsHorizontal from printer where printerid=" + resultBoard.BoardBaseInfo.PrinterId;
                DataTable tablePrinter = AccessHelper.dataTable(QueryPrinter, oleconn, tran);
                resultBoard.IsTransverse = Convert.ToBoolean(tablePrinter.Rows[0]["IsTransverse"]);
                //resultBoard.IsMiddle = Convert.ToBoolean(tablePrinter.Rows[0]["IsMiddle"]);
                resultBoard.PrinterName = Convert.ToString(tablePrinter.Rows[0]["PName"]);
                resultBoard.PrinterType = Convert.ToInt32(tablePrinter.Rows[0]["PrinterType"]);
               
                resultBoard.IsHorizontal = Convert.ToBoolean(tablePrinter.Rows[0]["IsHorizontal"]);

                //获取版的模板信息
                string QueryBoardTempleteSql = "select * from BoardTemplate where ID=" + boardTempleteID;
                DataTable tableTemplete = AccessHelper.dataTable(QueryBoardTempleteSql, oleconn, tran);
                resultBoard.BoardTemlpeteInfo = new BoardTemplate_Info() { TemplateId = Convert.ToInt32(tableTemplete.Rows[0]["ID"]), TemplateName = Convert.ToString(tableTemplete.Rows[0]["TemplateName"]) };


                //获取版上的照片信息
                resultBoard.PhotoS = new List<PhotoInfo_MakeBigPic>();
                string QueryPicMakeup = "select id,BarCodeStatus,X,Y,orderinfo.Priority as Priority,OrderName,Height,PixWidth,PixHeight,IsClearBox,dpi,IsReback,Width,orderinfo.OrderProductId as OrderProductId ,photoinfo.PhotoId as PhotoId ,PhotoName "
                + ",photoinfo.PicPath as PicPath,photoinfo.Remark as Remark,photoinfo.Status as Status,photoinfo.TotalNum as TotalNum,IsWhirl,FatherFolder,GranddadFolder,photoOrderNum,photoinfo.DXFContent,photoinfo.DXFFilePath from picmakeup,photoinfo,orderinfo where photoinfo.orderproductid=orderinfo.orderproductid and picmakeup.photoid=photoinfo.photoid and boardid= " + resultBoard.BoardBaseInfo.BoardId;
                DataTable tablePic = AccessHelper.dataTable(QueryPicMakeup, oleconn, tran);
                if (tablePic.Rows.Count > 0)
                {
                    for (int i = 0; i < tablePic.Rows.Count; i++)
                    {
                        PhotoInfo_MakeBigPic pm_makeBigPic = new PhotoInfo_MakeBigPic()
                        {
                            PmID = Convert.ToInt32(tablePic.Rows[i]["ID"]),
                            barCodeStatus = (SmallERP.COM.Status.PhotoBarCodeStatus)Convert.ToInt32(tablePic.Rows[i]["BarCodeStatus"]),
                            X = Convert.ToString(tablePic.Rows[i]["X"]),
                            Y = Convert.ToString(tablePic.Rows[i]["Y"]),
                            Priority = Convert.ToInt32(tablePic.Rows[i]["Priority"]),
                            OrderProductName = Convert.ToString(tablePic.Rows[i]["OrderName"]),
                            Location = new System.Drawing.Point(Convert.ToInt32(tablePic.Rows[i]["X"]), Convert.ToInt32(tablePic.Rows[i]["Y"])),
                            IsWhirl = Convert.ToBoolean(tablePic.Rows[i]["IsWhirl"])

                        };

                        int photoDPI = Convert.ToInt32(tablePic.Rows[i]["DPI"]);
                        int OrderProductid = Convert.ToInt32(tablePic.Rows[i]["OrderProductId"]);
                        string orderNumSql = "select count(photoid) from photoinfo where orderproductid= " + OrderProductid + " and photoid<=" + Convert.ToInt32(tablePic.Rows[i]["PhotoId"]);
                        int orderNum = (int)AccessHelper.ExecuteScalar(orderNumSql, oleconn, tran);
                        string allNumSql = "select count(photoid) from photoinfo where orderproductid= " + OrderProductid;
                        int allNum = (int)AccessHelper.ExecuteScalar(allNumSql, oleconn, tran);
                        pm_makeBigPic.OrderInOrderproduct = allNum.ToString() ;
                        pm_makeBigPic.BasePhotoInfo = new Photo_Info()
                        {
                            Height = Convert.ToDouble(tablePic.Rows[i]["Height"]),
                            IsClearBox = Convert.ToBoolean(tablePic.Rows[i]["IsClearBox"]),
                            IsReback = Convert.ToBoolean(tablePic.Rows[i]["IsReback"]),
                            Width = Convert.ToDouble(tablePic.Rows[i]["Width"]),
                            OrderProductId = Convert.ToInt32(tablePic.Rows[i]["OrderProductId"]),
                            PhotoId = Convert.ToInt32(tablePic.Rows[i]["PhotoId"]),
                            PhotoName = Convert.ToString(tablePic.Rows[i]["PhotoName"]),
                            PicPath = Convert.ToString(tablePic.Rows[i]["PicPath"]),
                            PixHeight = Convert.ToInt32(Convert.ToDecimal(tablePic.Rows[i]["PixHeight"]) / photoDPI * resultBoard.BoardBaseInfo.DPI),
                            PixWidth = Convert.ToInt32(Convert.ToDecimal(tablePic.Rows[i]["PixWidth"]) / photoDPI * resultBoard.BoardBaseInfo.DPI),
                            Remark = Convert.ToString(tablePic.Rows[i]["Remark"]),
                            Status = Convert.ToInt32(tablePic.Rows[i]["status"]),
                            TotalNum = Convert.ToInt32(tablePic.Rows[i]["TotalNum"]),
                            FatherFolder = Convert.ToString(tablePic.Rows[i]["FatherFolder"]),
                            GranddadFolder = Convert.ToString(tablePic.Rows[i]["GranddadFolder"]),
                            OrderNumInProduct = Convert.ToInt16(tablePic.Rows[i]["photoOrderNum"] is DBNull ? 0 : tablePic.Rows[i]["photoOrderNum"]),
                            DXFFilePath = Convert.ToString(tablePic.Rows[i]["DXFFilePath"] is  DBNull ?"":tablePic.Rows[i]["DXFFilePath"]) ,
                            DXFContent =(tablePic.Rows[i]["DXFContent"] is  DBNull? null:(byte[])(tablePic.Rows[i]["DXFContent"]))  

                        };



                        resultBoard.PhotoS.Add(pm_makeBigPic);



                    }
                }
                else
                {
                    string delBoard = "delete from board where boardid=" + resultBoard.BoardBaseInfo.BoardId;
                    int a = AccessHelper.ExecuteNonQuery(delBoard, oleconn, tran);
                    //return null;
                    resultBoard = null;
                }
                //检查下是否是access路径错误
                if (resultBoard!=null&&resultBoard.BoardBaseInfo.PicPath.IndexOf("\\") == -1)
                {
                    string delBoard = "update   board  set status =5  where boardid=" + resultBoard.BoardBaseInfo.BoardId;
                    int a = AccessHelper.ExecuteNonQuery(delBoard, oleconn, tran);
                    //return null;
                    resultBoard = null;
                }
               
                tran.Commit();
            }

            AccessHelper.CloseMyConnection(oleconn);
            return resultBoard;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static void GetOneBoardToClear()
        {
            BoardInfo_MakeBigPic resultBoard = new BoardInfo_MakeBigPic();
            int waitClearStatus = 0;


            OleDbConnection oleconn = AccessHelper.OpenMyConnection();
            using (var tran = oleconn.BeginTransaction())
            {
                string SeleteClearType = "select SysOrderPath  from SysSetting";
                string clearType = (string)AccessHelper.ExecuteScalar(SeleteClearType, oleconn, tran);
                if ("keep".Equals(clearType))
                {
                    return;
                }
                int waitProductStatus = (int)SmallERP.COM.Status.EnumBoardStatus.WaitingPrint;
                string getBoardSql = "select  * from board where IsClear=" + waitClearStatus + "and status=" + waitProductStatus + " order by PrintPriority desc,CreateTime";
                DataTable tableBoard = AccessHelper.dataTable(getBoardSql, oleconn, tran);
                int waitBoardCount = tableBoard.Rows.Count;
                if (waitBoardCount <= 0)
                {
                    return;
                }
                resultBoard.AllCount = waitBoardCount.ToString();
                int DPI = Convert.ToInt32(tableBoard.Rows[0]["DPI"]);
                resultBoard.BoardBaseInfo = new Board_Info()
                {

                    BoardId = Convert.ToInt32(tableBoard.Rows[0]["BoardId"]),

                    PicPath = Convert.ToString(tableBoard.Rows[0]["PicPath"]),
                    PrinterId = Convert.ToInt32(tableBoard.Rows[0]["PrinterId"]),
                    PrintNum = Convert.ToInt32(tableBoard.Rows[0]["PrintNum"]),
                    PrintPaperId = Convert.ToInt32(tableBoard.Rows[0]["PrintPaperId"]),
                    PrintPriority = Convert.ToInt32(tableBoard.Rows[0]["PrintPriority"]),
                    Remark = Convert.ToString(tableBoard.Rows[0]["Remark"]),
                    Status = Convert.ToInt32(tableBoard.Rows[0]["status"]),
                    WasteRate = Convert.ToInt32(tableBoard.Rows[0]["WasteRate"])
                };
                //string QueryPrinterSetting = "select * from PrinterSeting where printerid=" + resultBoard.BoardBaseInfo.PrinterId + " and papertypeid=" + resultBoard.BoardBaseInfo.PaperTypeId;
                //DataTable tablePS = AccessHelper.dataTable(QueryPrinterSetting, oleconn, tran);
                //if (tablePS.Rows.Count > 0)
                //{
                //    resultBoard.AddSharpen = Convert.ToInt32(tablePS.Rows[0]["Sharpening"]);
                //    resultBoard.IccPath = Convert.ToString(tablePS.Rows[0]["IccPath"]);
                //}
                //else
                //{
                //    resultBoard.AddSharpen = 0;
                //    resultBoard.IccPath = @"\\";
                //}
                //string QueryPrinter = "select IsTransverse,IsMiddle,PName,PrinterType from printer where printerid=" + resultBoard.BoardBaseInfo.PrinterId;
                //DataTable tablePrinter = AccessHelper.dataTable(QueryPrinter, oleconn, tran);
                //resultBoard.IsTransverse = Convert.ToBoolean(tablePrinter.Rows[0]["IsTransverse"]);
                ////resultBoard.IsMiddle = Convert.ToBoolean(tablePrinter.Rows[0]["IsMiddle"]);
                //resultBoard.PrinterName = Convert.ToString(tablePrinter.Rows[0]["PName"]);
                //resultBoard.PrinterType = Convert.ToInt32(tablePrinter.Rows[0]["PrinterType"]);
                resultBoard.PhotoS = new List<PhotoInfo_MakeBigPic>();

                string QueryPicMakeup = "select id,BarCodeStatus,X,Y,orderinfo.Priority as Priority,OrderName,OrderPath,Height,PixWidth,PixHeight,IsClearBox,dpi,IsReback,Width,orderinfo.OrderProductId as OrderProductId ,photoinfo.PhotoId as PhotoId ,PhotoName "
                + ",photoinfo.PicPath as PicPath,photoinfo.Remark as Remark,photoinfo.Status as Status,photoinfo.TotalNum as TotalNum,IsWhirl,FatherFolder,GranddadFolder,DXFContent,DXFFilePath from picmakeup,photoinfo,orderinfo where photoinfo.orderproductid=orderinfo.orderproductid and picmakeup.photoid=photoinfo.photoid and boardid= " + resultBoard.BoardBaseInfo.BoardId;
                DataTable tablePic = AccessHelper.dataTable(QueryPicMakeup, oleconn, tran);
                if (tablePic.Rows.Count > 0)
                {
                    for (int i = 0; i < tablePic.Rows.Count; i++)
                    {
                        PhotoInfo_MakeBigPic pm_makeBigPic = new PhotoInfo_MakeBigPic()
                        {
                            PmID = Convert.ToInt32(tablePic.Rows[i]["ID"]),
                            barCodeStatus = (SmallERP.COM.Status.PhotoBarCodeStatus)Convert.ToInt32(tablePic.Rows[i]["BarCodeStatus"]),
                            X = Convert.ToString(tablePic.Rows[i]["X"]),
                            Y = Convert.ToString(tablePic.Rows[i]["Y"]),
                            Priority = Convert.ToInt32(tablePic.Rows[i]["Priority"]),
                            OrderProductName = Convert.ToString(tablePic.Rows[i]["OrderName"]),
                            Location = new System.Drawing.Point(Convert.ToInt32(tablePic.Rows[i]["X"]), Convert.ToInt32(tablePic.Rows[i]["Y"])),
                            IsWhirl = Convert.ToBoolean(tablePic.Rows[i]["IsWhirl"]),
                            OrderPath = Convert.ToString(tablePic.Rows[i]["OrderPath"])

                        };

                        int photoDPI = Convert.ToInt32(tablePic.Rows[i]["DPI"]);
                        int OrderProductid = Convert.ToInt32(tablePic.Rows[i]["OrderProductId"]);
                        string orderNumSql = "select count(photoid) from photoinfo where orderproductid= " + OrderProductid + " and photoid<=" + Convert.ToInt32(tablePic.Rows[i]["PhotoId"]);
                        int orderNum = (int)AccessHelper.ExecuteScalar(orderNumSql, oleconn, tran);
                        string allNumSql = "select count(photoid) from photoinfo where orderproductid= " + OrderProductid;
                        int allNum = (int)AccessHelper.ExecuteScalar(allNumSql, oleconn, tran);
                        pm_makeBigPic.OrderInOrderproduct =  allNum.ToString();
                        pm_makeBigPic.BasePhotoInfo = new Photo_Info()
                        {
                            Height = Convert.ToDouble(tablePic.Rows[i]["Height"]),
                            IsClearBox = Convert.ToBoolean(tablePic.Rows[i]["IsClearBox"]),
                            IsReback = Convert.ToBoolean(tablePic.Rows[i]["IsReback"]),
                            Width = Convert.ToDouble(tablePic.Rows[i]["Width"]),
                            OrderProductId = Convert.ToInt32(tablePic.Rows[i]["OrderProductId"]),
                            PhotoId = Convert.ToInt32(tablePic.Rows[i]["PhotoId"]),
                            PhotoName = Convert.ToString(tablePic.Rows[i]["PhotoName"]),
                            PicPath = Convert.ToString(tablePic.Rows[i]["PicPath"]),
                            PixHeight = Convert.ToInt32(Convert.ToDecimal(tablePic.Rows[i]["PixHeight"]) / photoDPI * resultBoard.BoardBaseInfo.DPI),
                            PixWidth = Convert.ToInt32(Convert.ToDecimal(tablePic.Rows[i]["PixWidth"]) / photoDPI * resultBoard.BoardBaseInfo.DPI),
                            Remark = Convert.ToString(tablePic.Rows[i]["Remark"]),
                            Status = Convert.ToInt32(tablePic.Rows[i]["status"]),
                            TotalNum = Convert.ToInt32(tablePic.Rows[i]["TotalNum"]),
                            FatherFolder = Convert.ToString(tablePic.Rows[i]["FatherFolder"]),
                            GranddadFolder = Convert.ToString(tablePic.Rows[i]["GranddadFolder"]),
                            DXFFilePath = Convert.ToString(tablePic.Rows[i]["DXFFilePath"])
                        };
                             if((tablePic.Rows[i]["DXFFilePath"] is DBNull) )
                             {
                                 pm_makeBigPic.BasePhotoInfo.DXFContent = null;
                             }
                             else
                             {
                                 pm_makeBigPic.BasePhotoInfo.DXFContent = (byte[])tablePic.Rows[i]["DXFContent"];
                             }
                    


                        resultBoard.PhotoS.Add(pm_makeBigPic);



                    }
                }
                else
                {
                    string delBoard = "delete from board where boardid=" + resultBoard.BoardBaseInfo.BoardId;
                    int a = AccessHelper.ExecuteNonQuery(delBoard, oleconn, tran);
                    //return null;
                    resultBoard = null;
                    tran.Commit();
                    return;
                }

                if ("keep".Equals(clearType))
                {
                    //不改变
                }
                else if ("delete".Equals(clearType))
                {
                    //直接删除
                    int waitProductstatus = (int)SmallERP.COM.Status.PhotoStatus.WaitProductBigPic;
                    int waiPanban = (int)SmallERP.COM.Status.PhotoStatus.WaitPB;
                    foreach (PhotoInfo_MakeBigPic photo in resultBoard.PhotoS)
                    {

                        string CheckOrderPhotosql = "select count(photoid) from photoinfo where orderproductid=" + photo.BasePhotoInfo.OrderProductId + " and (status=" + waiPanban + " or status="+waitProductstatus+" ) and picpath='" + photo.BasePhotoInfo.PicPath + "'";

                        int ValOrderPhoto = (int)AccessHelper.ExecuteScalar(CheckOrderPhotosql);
                        if (ValOrderPhoto == 0)
                        {
                            string orderFromPathSQL = "select OrderPath from orderinfo where orderproductid=" + photo.BasePhotoInfo.OrderProductId;

                            string Frompath = (string)AccessHelper.ExecuteScalar(orderFromPathSQL);
                            ////////string orderToPath = photo.BasePhotoInfo.PicPath.Replace(photo.OrderPath, clearType);
                            //////string orderToPath = clearType + "\\" + photo.OrderProductName.Trim('\\');
                            ////////强制删掉整个产品文件夹
                            //////if (!string.IsNullOrEmpty(orderToPath))
                            //////{
                            //////    // DeleteDirectory(path);
                            //////    if (Directory.Exists(Frompath))
                            //////    {
                            //////        if (!Directory.Exists(orderToPath))
                            //////        {
                            //////            Directory.CreateDirectory(orderToPath);
                            //////        }
                            //////            //bool b = MoveFileEx(Frompath, orderToPath, 1);
                            //////        MoveDir(Frompath, orderToPath);
                            //////    }
                            //////}
                            string fromFile = photo.BasePhotoInfo.PicPath;

                            if (File.Exists(fromFile))
                            {

                                File.Delete(fromFile);

                            }
                            string DirPath = Path.GetDirectoryName(fromFile);
                            string[] filesjpg = Directory.GetFiles(DirPath, "*.jpg");
                            string[] filejpeg = Directory.GetFiles(DirPath, "*.jpeg");

                            if (filesjpg.Count() == 0 && filejpeg.Count() == 0)
                            {
                                string orderToPath = clearType + "\\" + photo.OrderProductName.Trim('\\');
                                //强制删掉整个产品文件夹
                                if (!string.IsNullOrEmpty(orderToPath))
                                {
                                    // DeleteDirectory(path);
                                    if (Directory.Exists(Frompath))
                                    {
                                        Directory.Delete(Frompath,true);
                                       
                                    }
                                }

                            }

                        }


                        //}

                    }
                }
                else
                {
                    //移动目录


                    //int waitProductstatus = (int)SmallERP.COM.Status.PhotoStatus.WaitProductBigPic;
                    ////int errorstatus = (int)SmallERP.COM.Status.PhotoStatus.e;
                    //int waiPanban = (int)SmallERP.COM.Status.PhotoStatus.WaitPB;
                    //foreach (PhotoInfo_MakeBigPic photo in resultBoard.PhotoS)
                    //{

                    //    string CheckOrderPhotosql = "select count(photoid) from photoinfo where orderproductid=" + photo.BasePhotoInfo.OrderProductId + " and (status=" + waiPanban + " or status = " + waitProductstatus + ") and picpath='" + photo.BasePhotoInfo.PicPath + "'";

                    //    int ValOrderPhoto = (int)AccessHelper.ExecuteScalar(CheckOrderPhotosql);
                    //    if (ValOrderPhoto == 0)
                    //    {
                    //        string orderFromPathSQL = "select OrderPath from orderinfo where orderproductid=" + photo.BasePhotoInfo.OrderProductId;

                    //        string Frompath = (string)AccessHelper.ExecuteScalar(orderFromPathSQL);
                           
                    //        string fromFile = photo.BasePhotoInfo.PicPath;
                    //        string toFile = photo.BasePhotoInfo.PicPath.Replace(photo.OrderPath, clearType + "\\" + photo.OrderProductName.Trim('\\'));
                    //        string DirPathTo = Path.GetDirectoryName(toFile);
                    //        if (!Directory.Exists(DirPathTo))
                    //        {
                    //            Directory.CreateDirectory(DirPathTo);
                    //        }
                    //        if (File.Exists(fromFile))
                    //        {
                    //            bool isMove = MoveFileEx(fromFile, toFile, 2);
                    //            if (!isMove)
                    //            {
                    //                File.Copy(fromFile, toFile, true);
                    //                File.Delete(fromFile);
                    //            }
                    //        }
                    //        //string DirPath = Path.GetDirectoryName(fromFile);
                    //        //string[] filesjpg = Directory.GetFiles(DirPath, "*.jpg");
                    //        //string[] filejpeg = Directory.GetFiles(DirPath, "*.jpeg");
                    //        string CheckOrdersql = "select count(photoid) from photoinfo where orderproductid=" + photo.BasePhotoInfo.OrderProductId + " and (status=" + waiPanban + " or status="+waitProductstatus+")";

                    //        int ValOrder = (int)AccessHelper.ExecuteScalar(CheckOrdersql);
                    //        if (ValOrder == 0)
                    //        {
                    //            string orderToPath = clearType + "\\" + photo.OrderProductName.Trim('\\');
                    //            //强制删掉整个产品文件夹
                    //            if (!string.IsNullOrEmpty(orderToPath))
                    //            {
                    //                // DeleteDirectory(path);
                    //                if (Directory.Exists(Frompath))
                    //                {
                    //                    if (!Directory.Exists(orderToPath))
                    //                    {
                    //                        Directory.CreateDirectory(orderToPath);
                    //                    }
                    //                    //bool b = MoveFileEx(Frompath, orderToPath, 1);
                    //                    MoveDir(Frompath, orderToPath);
                    //                }
                    //            }
                    //            //if (Directory.Exists(Frompath))
                    //            //{
                    //            //    Directory.Delete(Frompath, true);
                    //            //}
                    //        }

                    //    }


                    //    //}

                    //}


                    //string updateBoard = "update board set  IsClear=1 where boardid=" + resultBoard.BoardBaseInfo.BoardId;
                    //int a = AccessHelper.ExecuteNonQuery(updateBoard, oleconn, tran);

                }


                tran.Commit();
            }


            AccessHelper.CloseMyConnection(oleconn);
            return;
        }
        public static void CopyDir(string fromDir, string toDir)
        {
            if (!Directory.Exists(fromDir))
            {
                return;

            }
            if (!Directory.Exists(toDir))
                return;
            string[] files = Directory.GetFiles(fromDir);
            foreach (string formFileName in files)
            {
                string fileName = Path.GetFileName(formFileName);
                string toFileName = Path.Combine(toDir, fileName);
                File.Copy(formFileName, toFileName,true);
            }
            string[] fromDirs = Directory.GetDirectories(fromDir);
            foreach (string fromDirName in fromDirs)
            {
                string dirName = Path.GetFileName(fromDirName);
                string toDirName = Path.Combine(toDir, dirName);
                CopyDir(fromDirName, toDirName);
            }
        }
        public static void MoveDir(string fromDir, string toDir)
        {
            if (!Directory.Exists(fromDir))
                return;
            bool isDel = true;
            try
            {
                CopyDir(fromDir, toDir);
            }
            catch(Exception ex)
            {
                WriteLogForCheck.WriteLogFile(ex.Message);
                isDel = false;
 
            }
            if (isDel)
            {
                Directory.Delete(fromDir, true);
            }
        }
        ///
        /// <summary>
        /// 解坐标X、Y
        /// </summary>
        /// <param name="strInput"></param>
        /// <returns></returns>
        public string EncryptPoint(string strInput)
        {
            if (string.IsNullOrEmpty(_dogCode))
            {
                try
                {
                    _dogCode = GetDogCode();
                }
                catch (Exception)
                {
                    return string.Empty;
                }

                if (string.IsNullOrEmpty(_dogCode))
                    return string.Empty;
            }
            string key = _dogCode.Substring(0, 8);//前八位为KEY
            string encryptDogCode = _dogCode.Substring(8);
            string dogKey = Decipher(encryptDogCode, key);

            return Decipher(strInput, dogKey);
        }

        const int MIN_ASC = 32;
        const int MAX_ASC = 126;
        const int NUM_ASC = 95;
        //解密
        public string Decipher(string strFromText, string key)
        {
            StringBuilder result = new StringBuilder();
            char[] random = key.ToCharArray();
            char[] from_text = strFromText.ToCharArray();
            char[] buf1 = new char[8];
            int offset;
            int str_len = 1;
            int i;
            int ch;

            str_len = from_text.Length;
            try
            {
                for (i = 0; i < str_len; i++)
                {
                    ch = (int)from_text[i];
                    if (ch >= MIN_ASC && ch <= MAX_ASC)
                    {
                        ch = ch - MIN_ASC;
                        offset = (NUM_ASC + 1) * random[i];
                        ch = (ch - offset) % NUM_ASC;
                        if (ch < 0)
                        {
                            ch = ch + NUM_ASC;
                        }
                        ch = ch + MIN_ASC;
                        buf1[i] = (char)ch;
                    }
                    else
                    {
                        buf1[i] = from_text[i];
                    }
                }
                foreach (var item in buf1)
                {
                    result.Append(item);
                }
            }
            catch (Exception)
            {
                result = new StringBuilder("");
            }

            return result.ToString();
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="inBoardList"></param>
        /// <returns></returns>
        public int DeleteBoards(List<int> inBoardList)
        {
            int rtnval = 0;
            //AccessHelper();
            OleDbConnection olecc = AccessHelper.OpenMyConnection();
            using (OleDbTransaction tran = olecc.BeginTransaction())
            {
                foreach (int boardid in inBoardList)
                {
                    string UpdatePhoto = "update photoinfo set status=" + (int)Status.PhotoStatus.WaitPB + " where photoid in(select photoid from picmakeup where boardid =" + boardid + ")";
                    int upInt = AccessHelper.ExecuteNonQuery(UpdatePhoto, olecc, tran);
                    if (upInt > 0)
                    {
                        string delBoard = "delete  from board where boardid =" + boardid;
                        int delInt = AccessHelper.ExecuteNonQuery(delBoard, olecc, tran);
                        if (delInt == 0)
                        {
                            rtnval = 0;

                        }
                        else
                        {
                            rtnval = 1;
                        }
                    }
                    else
                    {
                        string delBoard = "delete  from board where boardid =" + boardid;
                        int delInt = AccessHelper.ExecuteNonQuery(delBoard, olecc, tran);
                        if (delInt == 0)
                        {
                            rtnval = 0;

                        }
                        else
                        {
                            rtnval = 1;
                        }
                    }

                }
                if (rtnval == 0)
                {
                    tran.Rollback();
                }
                else
                {
                    tran.Commit();
                }
            }
            AccessHelper.CloseMyConnection(olecc);
            return rtnval;
        }
        /// <summary>
        /// 生成大图成功
        /// </summary>
        /// <param name="BoardId"></param>
        /// <returns></returns>
        internal int MakeBigPicSusscess(BoardInfo_MakeBigPic boardInfo)
        {
            int result = 0;
            ////改大板的状态以及照片的状态 
            //using (smallerpDataContext db = new smallerpDataContext())
            //{
            //    Board b = db.Board.FirstOrDefault(bT => bT.BoardId == boardInfo.BoardBaseInfo.BoardId);
            //    if (b != null)
            //    {
            //        b.picPath = boardInfo.BoardBaseInfo.PicPath;
            //        b.Status = (int)SmallERP.COM.Status.EnumBoardStatus.WaitingPrint;
            //    }
            //    foreach (var pi in boardInfo.PhotoS)
            //    {

            //        photoInfo p = db.photoInfo.FirstOrDefault(pt => pt.PhotoId == pi.BasePhotoInfo.PhotoId);
            //        if (p != null)
            //        {
            //            p.Status = (int)SmallERP.COM.Status.PhotoStatus.Producted;
            //        }
            //    }

            //    try
            //    {
            //        db.SaveChanges();
            //    }
            //    catch (Exception)
            //    {
            //        result = -2;
            //    }
            //}

            OleDbConnection oleconn = AccessHelper.OpenMyConnection();
            using (var tran = oleconn.BeginTransaction())
            {
                string updateBoard = "update board set picPath='" + boardInfo.BoardBaseInfo.PicPath + "', Status=" + (int)SmallERP.COM.Status.EnumBoardStatus.WaitingPrint + " where boardid=" + boardInfo.BoardBaseInfo.BoardId;
                int boardReault = AccessHelper.ExecuteNonQuery(updateBoard, oleconn, tran);
                if (boardReault > 0)
                {
                    string updatePhotoInfo = "update photoinfo set status=" + (int)SmallERP.COM.Status.PhotoStatus.Producted + ",printerid=" + boardInfo.BoardBaseInfo.PrinterId + " where photoid in(select photoid from picmakeup where boardid=" + boardInfo.BoardBaseInfo.BoardId + ")";
                    int PhotoInfoResult = AccessHelper.ExecuteNonQuery(updatePhotoInfo, oleconn, tran);
                    if (PhotoInfoResult > 0)
                    {

                        result = 1;
                        tran.Commit();
                    }
                    else
                    {
                        result = 0;
                        tran.Rollback();
                    }
                }
                else
                {
                    result = 0;
                    tran.Rollback();
                }
                if (result == 1)
                {
                    //int waitProductstatus = (int)SmallERP.COM.Status.PhotoStatus.WaitProductBigPic;
                    //int waiPanban = (int)SmallERP.COM.Status.PhotoStatus.WaitPB;
                    //foreach (PhotoInfo_MakeBigPic photo in boardInfo.PhotoS)
                    //{
                    //    //string checkPhotos = "select count(photoid) from photoinfo where picpath='" + photo.BasePhotoInfo.PicPath + "'  and status=" + waitProductstatus;
                    //    //int Val = (int)AccessHelper.ExecuteScalar(checkPhotos);
                    //    //if (Val == 0)
                    //    //{
                    //    ///可以删除照片
                    //    //File.Delete(photo.BasePhotoInfo.PicPath);
                    //    string CheckOrdersql = "select count(photoid) from photoinfo where orderproductid=" + photo.BasePhotoInfo.OrderProductId + " and (status=" + waitProductstatus + " or status =" + waiPanban+")";

                    //    int ValOrder = (int)AccessHelper.ExecuteScalar(CheckOrdersql);
                    //    if (ValOrder == 0)
                    //    {
                    //        string orderPath = "select OrderPath from orderinfo where orderproductid=" + photo.BasePhotoInfo.OrderProductId;
                    //        string path = (string)AccessHelper.ExecuteScalar(orderPath);
                    //        //强制删掉整个产品文件夹
                    //        if (!string.IsNullOrEmpty(path))
                    //        {
                    //            DeleteDirectory(path);
                    //        }
                    //    }

                    //    //}

                    //}

                }
                AccessHelper.CloseMyConnection(oleconn);
                return result;

            }
        }
        static void DeleteDirectory(string dir)
        {
            if (Directory.Exists(dir))
            {
                if (Directory.GetDirectories(dir).Length == 0 && Directory.GetFiles(dir).Length == 0)
                {
                    if (Directory.Exists(dir))
                    {
                        Directory.Delete(dir);
                    }
                    return;
                }
                else if (Directory.GetDirectories(dir).Length == 0 && Directory.GetFiles(dir).Length != 0)
                {
                    string[] strFiles = Directory.GetFiles(dir);
                    foreach (string str in strFiles)
                    {
                        //if (str.ToUpper().IndexOf(("Thumbs.db").ToUpper()) >= 0)
                        //{
                        //    File.Delete(str);
                        //}
                        //if (str.ToUpper().EndsWith("TXT"))
                        //{
                        //    File.Delete(str);

                        //}
                        //if (str.ToUpper().EndsWith("INI"))
                        //{
                        File.Delete(str);

                        //}
                    }
                }

                foreach (string var in Directory.GetDirectories(dir))
                {

                    DeleteDirectory(var);
                }
                foreach (string var in Directory.GetFiles(dir))
                {
                    if (File.Exists(var))
                    {
                        File.Delete(var);
                    }
                    //File.Delete(var);
                }
                if (Directory.Exists(dir))
                {
                    Directory.Delete(dir);
                }
            }
            // Directory.Delete(dir);
        }

        public void ReProduct(List<int> inBoardList)
        {
            int rtnval = 0;
            //AccessHelper();
            OleDbConnection olecc = AccessHelper.OpenMyConnection();
            using (OleDbTransaction tran = olecc.BeginTransaction())
            {
                foreach (int boardid in inBoardList)
                {
                    
                        string UpdateBoard = "Update    board set status="+ (int)Status.EnumBoardStatus.waitProduct+" where boardid =" + boardid;

                        int delInt = AccessHelper.ExecuteNonQuery(UpdateBoard, olecc, tran);
                }
                tran.Commit();
            }
            AccessHelper.CloseMyConnection(olecc);
           
        }
        public void ReNameBoardPath(int inBoardid,string inPath)
        {
            int rtnval = 0;
            //AccessHelper();
            OleDbConnection olecc = AccessHelper.OpenMyConnection();
            using (OleDbTransaction tran = olecc.BeginTransaction())
            {

                string UpdateBoard = "Update    board set picpath='" + inPath + "' where boardid =" + inBoardid;

                    int delInt = AccessHelper.ExecuteNonQuery(UpdateBoard, olecc, tran);
                
                tran.Commit();
            }
            AccessHelper.CloseMyConnection(olecc);

        }
    }
}
